import useInstance from '@/hooks/useInstance'
import { ElForm } from 'element-plus'
import { ref, reactive, onMounted, onBeforeMount, onUpdated } from 'vue'
import {
    AddArticleModel,
    ArticleModel,
    ArticleParam
} from '@/api/cms/article/ArticleModel'
import type { UploadProps } from 'element-plus'
import { getParentCategoryApi } from '@/api/cms/category/category'
import { Result, StatusCode } from '@/http/request'
import {
    addArticleApi,
    editArticleApi,
    getArticleApi,
    getUploadUrlApi
} from '@/api/cms/article/article'
import { getSelectTagListApi } from '@/api/cms/tag/tag'
import { SelectTag } from '@/api/cms/tag/TagModel'
import { useRoute, useRouter } from 'vue-router'
import { EditType, Title } from '@/types/BaseEnum'
import { tabStore } from '@/store/tabs'
import { getSessionStorage } from '@/utils/sessionStore'
import { getToken } from '@/utils/auth'

export default function useArticleAdd(addModel: ArticleModel) {
    const router = useRouter()
    const route = useRoute()
    const tStore = tabStore()

    const { global } = useInstance()

    const uploadUrl = ref('')

    const headerObj = { Authorization: 'Bearer ' + getToken() }

    const formTitle = Title.ADD

    const treeData = reactive({
        data: []
    })

    const tagData = reactive({
        data: Array<SelectTag>()
    })

    // 表单ref属性
    const addArticleForm = ref<InstanceType<typeof ElForm>>()

    const onConfirm = () => {
        addArticleForm.value?.validate((valid) => {
            if (valid) {
            }
        })
    }

    // 获取分类的数据
    const getTreeData = async () => {
        let res = await getParentCategoryApi()
        if (res && res.code == StatusCode.Success) {
            treeData.data = res.data
            treeData.data.shift()
        }
    }

    // 获取标签数据
    const getSelectTagList = async () => {
        let res = await getSelectTagListApi()
        if (res && res.code == StatusCode.Success) {
            tagData.data = res.data
            // console.log(tagData)
        }
    }

    const handleImgSuccess: UploadProps['onSuccess'] = (res, uploadFile) => {
        // console.log('upload response', response)
        // console.log('uploadFile=', uploadFile)
        // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        // console.log(uploadFile)
        if (res && res.code == StatusCode.Success) {
            addModel.img = res.data[0]
            global.$message({
                message: '上传成功！',
                type: 'success'
            })
        } else {
            global.$message({
                message: res.msg,
                type: 'error'
            })
        }
    }

    const beforeImgUpload: UploadProps['beforeUpload'] = (rawFile) => {
        // console.log('rawFile=' + rawFile)
        // image/jpeg image/png
        if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png') {
            if (rawFile.size / 1024 / 1024 > 4) {
                global.$message({
                    message: '图片大小不能超过4MB！',
                    type: 'error'
                })
                return false
            }
            return true
        } else {
            global.$message({
                message: '必须是JPG、PNG格式的图片！',
                type: 'error'
            })
            return false
        }
    }

    const editorContent = (value: string) => {
        addModel.content = value
        // console.log('编辑内容：' + addModel.content)
    }

    // 保存
    const save = async () => {
        addArticleForm.value?.validate(async (valid) => {
            if (valid) {
                console.log('保存：', addModel)
                let tags: string = ''
                if (addModel.tag.length > 0) {
                    // addModel.tag.forEach((key, item: any) => {
                    //     tags.push(parseInt(key))
                    // })
                    tags = addModel.tag.join(',')
                }
                const saveParam = reactive<AddArticleModel>({
                    id: 0,
                    title: addModel.title,
                    status: parseInt(addModel.status),
                    tag_ids: tags,
                    img: addModel.img,
                    key_word: addModel.key_word,
                    category_id: addModel.category_id,
                    description: addModel.description,
                    content: addModel.content
                })
                console.log('保存', saveParam)
                let res: Result
                res = await addArticleApi(saveParam)
                if (res && res.code == StatusCode.Success) {
                    close()

                    router.push({ path: '/cms/article' })
                    // 信息提示
                    global.$message({ message: res.msg, type: 'success' })
                }
            }
        })
    }

    const close = () => {
        tStore.delTab(route.path, route.name as string)

        // 跳转路由
        router.push({ path: '/cms/article' })
    }

    const getUploadUrl = () => {
        uploadUrl.value = getUploadUrlApi()
    }

    onBeforeMount(async () => {
        await getSelectTagList()
        await getTreeData()
        await getUploadUrl()
    })

    return {
        formTitle,
        editorContent,
        headerObj,
        uploadUrl,
        treeData,
        tagData,
        onConfirm,
        addArticleForm,
        handleImgSuccess,
        beforeImgUpload,
        close,
        save
    }
}
